package ru.urfc.portal.services;

import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timer;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.urfc.portal.dao.BasePersistence;
import ru.urfc.portal.dao.impl.BaseDao;
import ru.urfc.portal.model.Client;
import ru.urfc.portal.model.Branch;
import ru.urfc.portal.model.NotificationSettings;
import ru.urfc.portal.model.accounting.Contragent;
import ru.urfc.portal.model.accounting.Invoice;
import ru.urfc.portal.model.admins.User;
import ru.urfc.portal.model.documents.Document;
import ru.urfc.portal.model.radio.Device;
import ru.urfc.portal.model.radio.DeviceCertificate;
import ru.urfc.portal.model.radio.NetLicense;
import ru.urfc.portal.model.radio.NetWithLicense;
import ru.urfc.portal.operations.DocumentContentService;
import services.DMSDocumentExternalInfo;

@Stateless
public class RefreshDocStates {
	
	public boolean dummyDebug = false; 
	public boolean debug = false;
	public boolean debugEmail = false;
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@PersistenceContext(name = "sys", unitName = "sys")
	public EntityManager sys;

	public boolean tryGetTestDocState(EntityManager sys, Long dmsId, DmsManager dmsMgr) {
		DmsTestEntity dte = (DmsTestEntity)sys.createQuery("SELECT d FROM DmsTestEntity d WHERE d.id =:id")
		.setParameter("id", dmsId).getSingleResult();
		if (dte != null) {
			dmsMgr.lc = dte.lc;
			return true;
		} else {
			return false;
		}
	}
	
	private Session session;

	@SuppressWarnings("unused")
	@Schedule(second = "0", minute = "0", hour = "*/1", dayOfWeek = "*", dayOfMonth = "*", month = "*", year = "*", info = "MyRefresh")
//	@Schedule(second = "*/15", minute = "*", hour = "*", dayOfWeek = "*", dayOfMonth = "*", month = "*", year = "*", info = "RefreshTimer")
	public void refreshStates(final Timer t) {
		logger.info("Refresh doc states from DMS");
//		StringWriter sw = new StringWriter();
//		dcs.htmlContent(32, sw);
//		logger.info("Cnt: {}", sw.toString());
//		if (true) return;
		
		session = null;
		try {
			InitialContext ic = new InitialContext();
			session = (Session) ic.lookup("mail/MyMailSession"); // "java:comp/env/mail/MyMailSession";
			refreshStates(sys);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void refreshDummyStates(EntityManager sys) {
		String docQ = "select d from Document d where d.state = :state";
		Query query = sys.createQuery(docQ).setParameter("state", DmsMdb.getInProgressState(sys));
		List<Document> docs = query.getResultList();
		for (Document document : docs) {
			logger.info("State changed for {}", document.getId());
			document.setState(DmsMdb.getSatisfiedState(sys));
			sys.persist(document);
			sendEmail(sys, document);
		}
	}

	public void refreshStates(EntityManager sys) {
		if (dummyDebug) {
			refreshDummyStates(sys);
			return;
		}
		String docQ = "select d from Document d where d.dms is not null";
		Query query = sys.createQuery(docQ);
		List<Document> docs = query.getResultList();
		DmsManager dmsMgr = new DmsManager();
		for (Document document : docs) {
			if (debug ? tryGetTestDocState(sys, Long.parseLong(document.dms), dmsMgr): dmsMgr.tryGetDocumentLC(document.dms)) {
				if ( !dmsMgr.lc.equals(document.lc)) {
					document.lc = dmsMgr.lc;
					DmsMdb.setDocState(sys, document, dmsMgr.lc);
					document.incomingNumber = dmsMgr.incomingNumber;
					document.incomingDate = dmsMgr.incomingDate;
					sys.persist(document);
					sendEmail(sys, document);
				}
			}
		}
	}
	private SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");

	public void sendEmail(EntityManager sys, Document doc) {
		String status = doc.lc != null ? doc.lc : doc.getState().getText();
		List<User> users = NotificationTimer.getUsers(sys, doc.getClient());
		for (User user : users) {
			String subj = String.format("РЧЦ УрФО. Статус вашей заявки № %s  изменен на '%s'",
					doc.getOutgoingNumber(), status);
			final String rawOutgoingNumber = doc.getOutgoingNumber();
			final String outgoingNumber = rawOutgoingNumber == null || rawOutgoingNumber.length() == 0
					? "---"
					: rawOutgoingNumber;
			final Date rawOutgoingDate = doc.getOutgoingDate();
			final String outgoingDate = rawOutgoingDate == null ? "---" : df.format(rawOutgoingDate);
			String body = String.format("Уважаемый Клиент РЧЦ УрФО!\n\nИнформируем Вас о том, что "
				+ "%s статус вашей заявки № %s от %s изменен на '%s'" 
				+ "\n\nС уважением,\nПортал РЧЦ УрФО\nportal@urfc.ru\nhttps://portal.urfc.ru/",
				df.format(new Date()), outgoingNumber, outgoingDate, status);
 
			if (debugEmail) {
				System.out.println("Email to " + user.getEmail() + " " + subj + " " + body);
				continue;
			}
			NotificationTimer.sendEmail(session, user.getEmail(), subj, body);
		}
		
	}
}
